/**
 * 系统配置  组织管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>组织管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索/添加筛选 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="searchForm.org_no" placeholder="输入组织编码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-search" @click="searchPlus">高级搜索</el-button>
        <el-button size="small" type="success" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="small" type="danger" @click="batchDelete()">批量删除</el-button>
        <el-button size="small"  @click="resetPage()">展示所有组织</el-button>
        <el-button size="small" type="primary" @click="exportData()">导出excel文件</el-button>
        <el-form-item>
        <el-upload class="upload-demo" action="/api/organization/import" 
        :headers="headers" :on-success="handlesuccess" :before-upload="beforeUpload" :show-file-list="showFile">
          <el-button size="small" type="primary">导入excel文件</el-button>
        </el-upload>
      </el-form-item>
      </el-form-item>
    </el-form>

    <el-container>
      <!-- 组织数据树状图 -->
      <el-aside width="200px" style="margin-top:40px">
        <Tree @getNodeData="getNodeData" :treeData="treeData" :label="label" :children="children"></Tree>
      </el-aside>

      <el-main>
        <!-- 组织列表 -->
        <el-table ref="multipleSelectable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange" size="small" highlight-current-row :row-key="getRowKeys">
          <el-table-column align="center" type="selection" width="60" :reserve-selection="true"></el-table-column>
          <el-table-column prop="id" label="序号" width="100" ></el-table-column>
          <el-table-column prop="org_no" label="组织编码"  width="130"></el-table-column>
          <el-table-column prop="org_name" label="组织名称" width="140"></el-table-column>
          <el-table-column prop="org_type" label="组织类型" width="140"></el-table-column>
          <el-table-column prop="parent_org" label="父级组织" width="140"></el-table-column>
          <el-table-column prop="org_attr" label="组织属性" width="140"></el-table-column>
          <el-table-column prop="org_category" label="组织分类" width="140"></el-table-column>
          <el-table-column prop="director" label="负责人" width="140"></el-table-column>
          <el-table-column prop="org_note" label="备注" width="140"></el-table-column>
          <el-table-column sortable prop="org_status" label="用户状态" width="140px" align="center">
            <template slot-scope="scope">
              <div><StatusSwitch :mystatus="scope.row.org_status" :mydisabled="true" @changeSwitch="changeSwitch"></StatusSwitch></div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200px">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteOrganization(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
      </el-main>
    </el-container>

    <!-- 编辑/新增界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="40%" @click="closeDialog" ref="editForm">
      <el-form label-width="100px" :model="editForm" :rules="rules" ref="editForm" :inline="true">
        <el-form-item label="组织编码" prop="org_no" width="100">
          <el-input v-model="editForm.org_no" placeholder="请输入组织编码" :disabled="isdisabled" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="组织名称" prop="org_name" width="100">
          <el-input v-model="editForm.org_name" auto-complete="off" placeholder="请输入组织名称" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="父级组织" prop="parent_org" width="100">
          <el-input v-model="editForm.parent_org" auto-complete="off" placeholder="请输入父级组织" @focus="showParentOrg" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="组织类型" prop="org_type" width="100">
          <el-select v-model="editForm.org_type" placeholder="请选择组织类型" style="width: 200px">
            <el-option v-for="item in organizationTypeData" :label="item" :value="item" :key="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="组织属性" prop="org_attr" width="100">
          <el-select v-model="editForm.org_attr" placeholder="请选择组织属性" style="width: 200px">
            <el-option v-for="item in organizationAttrData" :label="item" :value="item" :key="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="组织分类" prop="org_category" width="100">
          <el-select v-model="editForm.org_category" placeholder="请选择组织分类" style="width: 200px">
            <el-option v-for="item in organizationCategoryData" :label="item" :value="item" :key="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="director" width="100">
          <el-input v-model="editForm.director" auto-complete="off" placeholder="请输入父级组织" @focus="showDirector" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="org_note" width="100">
          <el-input v-model="editForm.org_note" auto-complete="off" placeholder="请输入备注" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item sortable prop="org_status" label="启用状态" align="center">
          <StatusSwitch :mystatus="editForm.org_status" :mydisabled="false" @changeSwitch="changeSwitch"></StatusSwitch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>

    <!-- 父类组织选择界面 -->
    <el-dialog title="选择父类组织" :visible.sync="parentFormVisible" width="50%" @click="closeDialog">
      <el-table ref="singleTable" :data="parentData" highlight-current-row @current-change="handleCurrentChange" style="width: 100%">
          <el-table-column prop="org_no" label="组织编码"  width="220"></el-table-column>
          <el-table-column prop="org_name" label="组织名称" width="220"></el-table-column>
          <el-table-column prop="org_type" label="组织类型" width="220"></el-table-column>
          <el-table-column prop="director" label="负责人" width="220"></el-table-column>
      </el-table>
      <el-pagination
      @size-change="pageSizeChange"
      @current-change="pageCurrentChange"
      :current-page="pageparm.currentPage"
      :page-sizes="[10, 15, 20]"
      :page-size="pageparm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageparm.total">
    </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="close('选择父类组织')">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submit('选择父类组织')">保存</el-button>
      </div>
    </el-dialog>

    <!-- 责任人选择界面 -->
    <el-dialog title="选择责任人" :visible.sync="directorVisible" width="40%" @click="closeDialog">
      <el-table ref="singleTable" :data="userData" highlight-current-row @current-change="handleCurrentChange" style="width: 100%">
          <el-table-column prop="no" label="编码"  width="220"></el-table-column>
          <el-table-column prop="name" label="名称" width="220"></el-table-column>
          <el-table-column prop="position" label="岗位" width="220"></el-table-column>
      </el-table>
      <Pagination :child-msg="pageparm" @callFather="getUserPage"></Pagination>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="close('选择责任人')">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submit('选择责任人')">保存</el-button>
      </div>
    </el-dialog>

    <!-- 高级搜索 -->
    <el-dialog title="高级搜索" :visible.sync="searchVisible" width="38%" @click="closeDialog">
      <el-form ref="searchForm" :model="searchForm" label-width="80px" inline>
        <el-form-item label="组织编码" prop="org_no" width="100">
          <el-input v-model="searchForm.org_no" placeholder="请输入组织编码" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="组织名称" prop="org_name" width="100">
          <el-input v-model="searchForm.org_name" auto-complete="off" placeholder="请输入组织名称" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="组织类型" prop="org_type" width="100">
          <el-select v-model="searchForm.org_type" placeholder="请选择组织类型" style="width: 200px">
            <el-option v-for="item in organizationTypeData" :label="item" :value="item" :key="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="父级组织" prop="parent_org" width="100">
          <el-input v-model="searchForm.parent_org" auto-complete="off" placeholder="请输入父级组织" @focus="showParentOrg" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="组织属性" prop="org_attr" width="100">
          <el-select v-model="searchForm.org_attr" placeholder="请选择组织属性" style="width: 200px">
            <el-option v-for="item in organizationAttrData" :label="item" :value="item" :key="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="组织分类" prop="org_category" width="100">
          <el-select v-model="searchForm.org_category" placeholder="请选择组织分类" style="width: 200px">
            <el-option v-for="item in organizationCategoryData" :label="item" :value="item" :key="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="director" width="100">
          <el-input v-model="searchForm.director" auto-complete="off" placeholder="请输入负责人" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item sortable prop="org_status" label="启用状态" align="center">
          <StatusSwitch :mystatus="searchForm.org_status" :mydisabled="false" @changeSwitch="changeSwitch_search"></StatusSwitch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="resetCondition">重置</el-button>
        <el-button @click='closeDialog("高级搜索")'>取消</el-button>
      </div>
    </el-dialog>

</div>
  
</template>

<script>
import Pagination from '../../components/Pagination'
import StatusSwitch from "../../components/orgComponet/StatusSwitch.vue";
import Tree from "../../components/Tree.vue";
export default {
  data() {
    var checkNo = (rule, value, callback) => {
      if(this.title == '新增组织'){
        console.log('1校验器title',this.title);
        this.$axios.get("/api/organization/no/"+value).then(Response => {
          if(Response.data.code==500) {
            callback();
          }
          callback(new Error('编码已存在！'));
        })
      }else{
        console.log('2校验器title',this.title);
        callback();
      }
    };
    return {
      loading: false, //是显示加载
      parentFormVisible: false,//控制父类选择框的显示与隐藏
      editFormVisible: false, //控制编辑页面显示与隐藏
      searchVisible:false,//控制高级搜索框的显示与隐藏
      directorVisible:false,//控制责任人显示与隐藏
      //父级组织数据
      parentData:{
        org_no: '',
        org_name: '',
        org_type: '',
        director: '',
      },
      userData: {
        no:'',
        name:'',
        position:''
      },
      showFile: false,
      isdisabled: '',
      title: '添加',
      tableDialogTitle:'',
      label:'org_name',
      children:'organizations',
      editForm: {
        org_no: '',
        org_name: '',
        org_type: '',
        parent_org: '',
        org_attr: '',
        org_category: '',
        director: '',
        org_note: '',
        org_status: '',
        token: localStorage.getItem('logintoken')
      },
      // rules表单验证
      rules: {
        org_name: [
          { required: true, message: '请输入组织名称', trigger: 'change' }
        ],
        org_no: [
          { required: true, message: '请输入组织代码', trigger: 'change' },
          { validator: checkNo, trigger: 'blur' }
        ]
      },
      searchForm: {
        org_no: '',
        org_name: '',
        org_type: '',
        parent_org: '',
        org_attr: '',
        org_category: '',
        director: '',
        org_note: '',
        org_status: '',
        token: localStorage.getItem('logintoken')
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      treeData: [],//树状图数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      // 选择责任人分页参数
      pageparm_user:{
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      tableData: [],//组织管理数据
      organizationTypeData:[],//组织类别数据
      organizationAttrData:[],//组织属性数据
      organizationCategoryData:[],//组织分类数据
      multipleSelection: [],//勾选组织ids
      parentData:[],//父类组织数据
      userData:[],
    }
  },
  // 注册组件
  components: {
    Pagination,
    StatusSwitch,
    Tree,
  },
  created() {
    this.getdata(),
    this.getAllData()
  },
  // 获取token
  computed: {
    headers() {
      return{
        "Authorization": localStorage.getItem('logintoken')
      }
    }
  },
  methods: {
    // 获取组织分页数据
    getdata() {
      this.loading = true
      this.$axios.get('/api/organization/'+this.pageparm.currentPage+'/'+this.pageparm.pageSize).then(res => {
      console.log(res);
      if(res.data.code == 200){
        this.tableData = res.data.data.list
        // 分页赋值
        this.pageparm.total = res.data.data.total
      }
      }).catch();
    },
    //获取组织类别数据
    getOrganizationTypeData(){
      this.$axios.get('/api/organization/type').then(res => {
        console.log(res);
        if(res.data.code == 200){
          this.organizationTypeData = res.data.data
      }
      }).catch();
    },
    //获取组织属性数据
    getOrganizationAttrData(){
      this.$axios.get('/api/organization/attr').then(res => {
        console.log(res);
        if(res.data.code == 200){
          this.organizationAttrData = res.data.data
      }
      }).catch();
    },
    //获取组织分类数据
    getOrganizationCategoryData(){
      this.$axios.get('/api/organization/category').then(res => {
        console.log(res);
        if(res.data.code == 200){
          this.organizationCategoryData = res.data.data
      }
      }).catch();
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage
      this.pageparm.pageSize = parm.pageSize
      this.getdata()
    },
    // 责任人分页插件事件
    getUserPage(parm) {
      this.pageparm_user.currentPage = parm.currentPage
      this.pageparm_user.pageSize = parm.pageSize
      this.getUserData()
    },
    // 搜索事件
    search() {
      this.$axios.post('/api/organization/search',this.searchForm).then(res => {
        console.log(res);
        if(res.data.code == 200){
          this.tableData = res.data.data
        }
        this.pageparm.total = res.data.data.length
        this.closeDialog('高级搜索');
      }).catch(()=>{});
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.getOrganizationTypeData();
      this.getOrganizationAttrData();
      this.getOrganizationCategoryData();
      this.editFormVisible = true
      console.log(row);
      if (row != undefined && row != 'undefined') {
        this.isdisabled = true
        this.title = '修改组织'
        this.editForm.org_no = row.org_no
        this.editForm.org_name = row.org_name
        this.editForm.org_type = row.org_type
        this.editForm.org_attr = row.org_attr
        this.editForm.parent_org = row.parent_org
        this.editForm.director = row.director
        this.editForm.org_category = row.org_category
        this.editForm.org_note = row.org_note
        this.editForm.org_status = row.org_status
      } else {
        this.isdisabled = false
        this.title = '新增组织'
        this.editForm.org_no = ''
        this.editForm.org_name = ''
        this.editForm.org_type = ''
        this.editForm.director = ''
        this.editForm.org_attr = ''
        this.editForm.parent_org = ''
        this.editForm.org_category = ''
        this.editForm.org_note = ''
        this.editForm.org_status = 'true'
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editForm) {
      this.$refs[editForm].validate(valid => {
        if (!valid) {
          this.$message.error("请正确填写表单！");
        }else{
          if(this.title=='新增组织'){
            this.$axios.post('/api/organization/add',this.editForm).then(res => {
            console.log(res);
            if(res.data.code == 200){
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
            }
            this.getdata();
            this.getAllData();
            this.editFormVisible = false
            }).catch();
          }else{
            this.$axios.put('/api/organization/update',this.editForm).then(res => {
              console.log(res);
              if(res.data.code == 200){
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
              }
              this.getdata();
              this.getAllData();
              this.editFormVisible = false
            }).catch();
          }
        }
      })
    },
    // 关闭编辑、增加弹出框
    closeDialog(title) {
      if(title == '高级搜索'){
        this.searchVisible = false
      }
      this.editFormVisible = false
    },
    changeSwitch(e){
        this.editForm.org_status = e
    },
    //搜索页面开关组件子传父
    changeSwitch_search(e){
        this.searchForm.org_status = e
    },
    //删除组织
    deleteOrganization(row){
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios.delete('/api/organization/delete/'+row.id).then(res => {
            if(res.data.code == 200){
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.pageparm.currentPage = 1
              this.pageparm.pageSize = 10
              this.getdata();
              this.getAllData();
              this.editFormVisible = false
            }
          }).cathch(()=>{});
        })
      .catch(()=>{})
    },
    //获取点击节点数据
    getNodeData(value){
      console.log(value);
      this.tableData= value
      this.pageparm.currentPage = 1
      this.pageparm.pageSize = 1
      this.pageparm.total = 1
    },
    //控制"选择父级组织"框
    showParentOrg(){
      this.parentFormVisible = true
      this.parentData = this.tableData
    },
    showDirector(){
      this.directorVisible = true;
      this.getUserData();
    },
    getUserData(){
      this.$axios.get('/api/user/'+this.pageparm_user.currentPage+'/'+this.pageparm_user.pageSize).then(res=>{
        console.log(res);
        if(res.data.code == 200){
          this.userData = res.data.data.list
          // 分页赋值
          this.pageparm_user.total = res.data.data.total
        }
      }).catch();
    },
    //"选择父级组织"框选中事件
    handleCurrentChange(val) {
      this.currentRow = val;
      console.log(this.currentRow);
    },
    //"选择父级组织"框保存
    submit(val){
      console.log(val);
      if(val == '选择父类组织'){
        this.editForm.parent_org = this.currentRow.org_name
        this.editForm.org_attr = this.currentRow.org_attr
        this.editForm.org_type = this.currentRow.org_type
        this.editForm.org_category = this.currentRow.org_category
        this.searchForm.parent_org = this.currentRow.org_name
        this.searchForm.director = this.currentRow.director
        this.parentFormVisible = false
      }else if(val == '选择责任人'){
        this.editForm.director = this.currentRow.name
        this.directorVisible = false
      }
    },
    //"选择父级组织"框取消
    close(val){
      if(val == '选择父类组织'){
        this.parentFormVisible = false
      }else if(val == '选择责任人'){
        this.directorVisible = false
      }
      
    },
    //获取被勾选的组织的id
    handleSelectionChange(organizations) {
      for(let index in organizations){
        this.multipleSelection[index] = organizations[index].id;
      }
      console.log(this.multipleSelection);
    },
    //批量删除
    batchDelete(){
      console.log(this.multipleSelection);
      if(this.multipleSelection.length==0){
            this.$message({
                type: "info",
                message: "请勾选需要删除的列",
            });
            return;
        }
        this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        })
        .then(() => {
            this.$axios.put("/api/organization/batchDelete",this.multipleSelection)
            .then((res) => {
              this.$refs.multipleSelectable.clearSelection();
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
                this.getdata();
                this.getAllData();
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$message.error("删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    pageSizeChange(val_pageSize) {
      console.log(`每页条数`,val_pageSize);
      this.$axios.get('/api/organization/'+this.pageparm.currentPage+'/'+val_pageSize).then(res => {
      console.log(res);
      if(res.data.code == 200){
        this.parentData = res.data.data.list
        // 分页赋值
        this.total = res.data.data.total
      }
      }).catch();
    },
    pageCurrentChange(val_currentPage) {
      console.log(`当前页:`,val_currentPage);
      this.$axios.get('/api/organization/'+val_currentPage+'/'+this.pageparm.pageSize).then(res => {
      console.log(res);
      if(res.data.code == 200){
        this.parentData = res.data.data.list
        // 分页赋值
        this.total = res.data.data.total
      }
      }).catch();
    },
    getRowKeys(row) {
      return row.id;
    },
    // 获取所有组织数据
    getAllData() {
        this.$axios.get('/api/organization/findParent').then(res => {
            console.log(res);
            if(res.data.code == 200){
                this.treeData = res.data.data;
            }
        }).catch();
    },
    //高级搜索事件
    searchPlus(){
      //显示高级搜索框
      this.searchVisible = true;
      this.searchForm.org_status = true;
      this.resetCondition();
      this.getOrganizationTypeData();
      this.getOrganizationAttrData();
      this.getOrganizationCategoryData();
    },
    resetCondition(){
      this.searchForm.org_no = ''
      this.searchForm.org_name = ''
      this.searchForm.org_type = ''
      this.searchForm.director = ''
      this.searchForm.org_attr = ''
      this.searchForm.parent_org = ''
      this.searchForm.org_category = ''
      this.searchForm.org_note = ''
      this.searchForm.org_status = 'true'
    },
    resetPage(){
      this.pageparm.currentPage = 1
      this.pageparm.pageSize = 10
      this.getdata();
    },
    //上传成功回调方法
    handlesuccess(res) {
      if (res.code == 200) {
        //刷新数据
        this.getdata();
        this.$message({
            type: "success",
            message: "操作成功！",
        });
      } else {
        this.$message({
            type: "info",
            message: res.message,
        });
      }
    },
    // 上传前判断文件格式
    beforeUpload(file) {
      console.log(file.type);
       const type = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!type) {
        this.$message.error("请上传EXCEL格式的文件!");
      }
      return type;
    },
    exportData(){
      this.$axios.get("/api/organization/export",{
        responseType: 'blob'
      }).then(response=> {
        //通过header中获取返回的文件名称
        let fileName = response.headers['content-disposition'].split(";")[1].split("filename=")[1]
        let blob = new Blob([response.data], { type: "application/vnd.ms-excel" })
        let downloadElement = document.createElement("a")
        var href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        //指定下载的文件的名称，切记进行decode
        downloadElement.download = decodeURI(fileName)
        document.body.appendChild(downloadElement)
        downloadElement.click()
        //移除临时创建对象，释放资源
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
      });
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.myInput{
  width:150px;
}
</style>

 